/**
 * OG Directory functions
 */

// Open a dialog box which allows the user to select the overgrowth data folder
function setOvergrowthDir(force) {
	dir = new air.File();
	if ( force == true ) {
		dir.addEventListener(air.Event.CANCEL, dirCanceled); 
	}
	dir.addEventListener(air.Event.SELECT, dirSelected); 
	dir.browseForDirectory("Select your overgrowth data directory");
	function dirCanceled() {
		setOvergrowthDir();
	}
	function dirSelected() {
		foldername = dir.nativePath.substring(dir.nativePath.length-4, dir.nativePath.length);
		if ( foldername == 'Data' ) {
			saveOvergrowthDir();
		}
		else {
			alert('You must select the <Overgrowth_root>/Data/ directory (Not the Overgrowth root itself)');
			setOvergrowthDir();
		}
	}
}
function saveOvergrowthDir() {
	var savedir = air.File.applicationStorageDirectory.resolvePath('overgrowthdir.txt');
	var stream = new air.FileStream();
	stream.open(savedir, air.FileMode.WRITE);
	stream.writeUTFBytes(dir.nativePath);
	stream.close();
}
function loadOvergrowthDir() {
	var loaddir = air.File.applicationStorageDirectory.resolvePath('overgrowthdir.txt');
	if ( loaddir.exists == true ) {
		var stream = new air.FileStream();
		stream.open(loaddir, air.FileMode.READ);
		var url = stream.readUTFBytes(stream.bytesAvailable);
		stream.close();
		dir = new air.File('file:///' + url);
		if ( dir.exists == false ) {
			setOvergrowthDir(true);
		}
	}
	else {
		setOvergrowthDir(true);
	}
}

/*
 * Downloading
 */

// Download a specific version of the mod
function downloadVersion(versionid) {
	for ( x in master.mods ) {
		if ( master.mods[x].json.id == versionid ) {
			master.mods[x].install();
		}
	}
}

// Uninstall a specific version of the mod
function uninstallVersion(versionid) {
	for ( x in master.mods ) {
		if ( master.mods[x].json.id == versionid ) {
			master.mods[x].uninstall();
		}
	}
}
// TODO: Update to use the uninstallVersion and downloadVersion methods (once they are made more standard)
function updateVersion(oldversionid) {
	for ( x in master.mods ) {
		if ( master.mods[x].json.id == oldversionid ) {
			var oldversion = master.mods[x];
			var newversion = master.mods[x].creation.getLatest();
		}
	}
	
	var dialog = $('<div id="uninstall-window"></div>').appendTo('body');
	dialog.dialog({
		modal: true,
		height: 0,
		width: 500,
		title: "Are you sure you want to upgrade?",
		draggable: false,
		resizable: false,
		closeOnEscape: false,
		buttons: {
			"No": function() {
				closeDialog();
			},
			"Yes": function() {
				doUpgrade();
			}
		}
	});
	
	function closeDialog() {
		dialog.dialog('close').remove();
	}
	
	function doUpgrade() {
		oldversion.uninstall(true, function(){
			closeDialog();
			newversion.install();
		});
	}
}